<script setup lang="ts">
import { PropType, reactive, ref } from 'vue'

import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'

import { useForm } from '@/hooks/web/useForm'

import { required } from '@/utils/formRules'

import { zcMarkOrderSeeApi } from '@/api/cy/xMarking'
// import { ucMyOrgListApi } from '@/api/cy/zichan'
import { sysDictRelsApi } from '@/api/dict'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { ucDeptListApi } from '@/api/uc/dept'
import { zcPastureListApi } from '@/api/fa/user'
// import { zcPastureListAdminApi } from '@/api/fa/pasture'
// import { adminFaUserListApi } from '@/api/fa/user'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label

/****************************** 变量 start ******************************/
const data = ref<any>({})
const dictRelsData = ref() // 联动数据
const breedSubData = ref([]) // 品种的枚举

const rules = reactive({
  pasture_org_id: [required],
  pasture_dept_name: [required],
  breed: [required],
  breed_sub: [required],
  amount: [required],
  number: [required],
  freight: [required],
  purpose: [required]
})

/****************************** 变量 end ******************************/

/****************************** 组件参数 start ******************************/
// 获取参数
const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})
console.log(props.detailSchema, dict)
/****************************** 组件参数 end ******************************/
// 调用查看接口获取信息
const getMedicalOrderSee = async () => {
  if (props.id) {
    const res = await zcMarkOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = await res.data
      // 明细信息处理一下，加上d_id
      console.log(res.data)
      await methods.setValues(data.value)
      DeptList(res.data.pasture_org_id)
      // onCustomer(res.data.pasture_org_id)
    }
  } else {
    data.value.state = '1'
    await methods.setValues(data.value)
  }
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = async (value) => {
  await breedGetSub(value)
  let formData = await methods.getFormData()
  await methods.setValues({ ...formData, breed_sub: '' })
}

const onCustomer = async (value) => {
  data.value.detailedData = [] // 删除明细的数据
  console.log(data.value, value, 'dada')
  newTreeData.value = []
  data.value.pasture_dept_id = ''
  data.value.pasture_dept_name = ''
  DeptList(value)
  await methods.setValues(data.value)
}
let newTreeData = ref<any[]>([])
const DeptList = async (val) => {
  // const loadingInstance = ElLoading.service(options)
  // const loadingMain = ElLoading.service({
  //   lock: true,
  //   text: 'Loading',
  //   background: 'rgba(0, 0, 0, 0.7)'
  // })
  const res = await ucDeptListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {
      // setTimeout(() => {
      //   loadingMain.close()
      // }, 500)
    })
  if (res) {
    newTreeData.value = res.data
    console.log(res.data, 'res')
  }
}
const schema: any = [
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择创建人（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [
        { field: 'org_name', label: '牧场名称', search: { show: true } }
        // { field: 'org_id', label: '牧场编码', search: { show: true } }
      ],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_name',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      nameField: 'pasture_dept_name',
      data: newTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      }
    }
  },
  {
    field: 'breed',
    label: '畜别',
    component: 'Select',
    componentProps: {
      options: dict.breed,
      onChange: breedChange
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    component: 'Select',
    componentProps: {
      options: breedSubData
    }
  },
  {
    field: 'number',
    label: '牲畜数量',
    component: 'Input'
  },
  {
    field: 'purpose',
    label: '用途',
    component: 'Select',
    componentProps: {
      options: dict.purpose
    }
  },
  {
    field: 'freight',
    label: '运费',
    component: 'Input'
  }
]
const { register, methods, elFormRef } = useForm({
  schema: schema
})

const getFormData = async () => {
  let formData = await methods.getFormData()
  // const sku = unref(skuRef)
  // let skuData = sku?.getData()
  // const goodsDetails = unref(goodsDetailsRef) //明细
  // let goods_details = goodsDetails?.getData()
  // let goods_tag = getGoodsTag()
  // let goods_details = data.value.goods_details
  // let goods_carousel = data.value.goods_carousel
  return { ...formData }
}

defineExpose({
  elFormRef,
  getFormData
})

// ************************** 初始化 start ******************************/
const init = async () => {
  // 获取关联关系
  await getDictRels()
  // 调用查看接口查询数据
  await getMedicalOrderSee()
  // 跟新畜别
  if (data.value.breed) {
    await breedGetSub(data.value.breed)
  }
}
init()
/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="register" />
    </ContentWrap>
  </div>
</template>
